package dao;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import model.Result;
import service.impl.CloseConnections;
import service.impl.Converter;

public class ResultDAO {
	static Connection currentConnection = null;
	static ResultSet rs = null;

	public static void save(List<Result> results) {
		PreparedStatement statement = null;

		try {
			currentConnection = ConnectionManager.getConnection();
			currentConnection.setAutoCommit(false);
			String sql = "insert into result(user_id, course_code, learning_method_id, answer_time, answer_day_of_week, study_period) values(?,?,?,?,?,?)";
			statement = currentConnection.prepareStatement(sql);
			for (Result result : results) {
				statement.setLong(1, result.getUserId());
				statement.setString(2, result.getCourseCode());
				statement.setLong(3, result.getLearningMethodId());
				statement.setDate(4, Converter.getSqlDate(result.getAnswerTime()));
				statement.setInt(5, getDayOfWeek(result.getAnswerTime()));
				statement.setDouble(6, result.getStudyPeriod());
				statement.addBatch();
			}
			statement.executeBatch();
			currentConnection.commit();

		} catch (BatchUpdateException s) {
			System.out.println("SQL statement is not executed!" + s);
		} catch (Exception e) {
			System.out.println("Exception in connection!: " + e);
		} finally {
			CloseConnections.closeAll(rs, statement, currentConnection);
		}
	}

	private static int getDayOfWeek(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		//Represent Sunday as 7, not 0
		return dayOfWeek == 0 ? 7 : dayOfWeek;
	}
}
